var alliedShips = new Array();
var hits = new Array();
var playersShipArray = new Array();
var turn = false;
var rotation = true;
var enemySankShipCount = 0;
var playerSankShipCount = 0;
var strikeAllow = false;
var arg = {
		info : "null"
};
var pollEnable = true;
var gameIndex;
var player1Name;
var player2Name;
var moveCount = 0;
var count = 60;
var countdown;
function ship(divArray, undropArray, direction, src) {
	this.coordinates = divArray;
	this.undropCoordinates = undropArray;
	this.isShot = false;
	this.health = this.coordinates.length;
	this.src = src;
	this.direction = direction;
}
function getShipAmountCounter(elem) {
	var x = parseInt($("#" + elem + ".div-table-col").html());
	return x;
}
function setShipAmountCounter(elem) {
	var x = parseInt($("#" + elem + ".div-table-col").html());
	x -= 1;
	$("#" + elem + ".div-table-col").html(x);
}
function clearDivs(divArray) {
	for ( var int = 0; int < divArray.length; int++) {
		$('#' + divArray[int]).html('');
	}
}
function clearDivs2(id, len, dir) {
	var firstId = parseInt(id.replace("id", ""));
	for ( var i = 0; i < len; i++) {
		if (dir) {
			$("#enemyid" + (firstId + i)).html('');
		} else {
			$("#enemyid" + (firstId + i * 10)).html('');
		}
	}
}
function lockShips() {
	$('img').draggable("option", "disabled", true);
	rotation = false;
}
function poll2() {
	$
	.ajax({
		url : "ready",
		type : "POST",
		data : {
			alliedShips : JSON.stringify(playersShipArray)
		},
		beforeSend : function(x) {
			if (x && x.overrideMimeType) {
				x.overrideMimeType("application/j-son;charset=UTF-8");
			}
		},
		success : function(data) {
			if (data === "error") {
				alert("You are not logged in. You will be redirected to lobby.");
				window.location = 'lobby.html';
			} else {
				gameIndex = getCurrentGameIndexFromLocalStorage();
				poll(arg);
			}
		}
	});
}
window.onbeforeunload = closeIt;
function closeIt() {
	$.ajax({
		type : "POST",
		url : 'game',
		async : false,
		data : {
			comand : "remove"
		},
	});
}
function countDownTimer() {
	countdown = setInterval(function() {
		if (strikeAllow) {
			$("#buttons").attr("class", "myBox");
			$("#buttons").css({
				"background-color" : "red",
				"color" : "#fff",
				"padding" : "5px"
			});
			$("#buttons").html(" " + count + " seconds remaining for move!")
			.show("slow");
			if (count == 0) {
				pollEnable = false;
				alert("You are kicked because of being afk!");
				$.ajax({
					type : "POST",
					url : 'game',
					data : {
						comand : "remove"
					},
					complete : function() {
						window.location = 'lobby.html';
					}
				});
			}
			count--;
		}
	}, 1000);
}
function poll(arg1) {
	if (pollEnable) {
		if (arg1["info"] === "null") {
			$
			.ajax({
				url : "test",
				type : "POST",
				data : arg1,
				dataType : "text",
				statusCode : {
					500 : function() {
						pollEnable = false;
						alert("Your opponent has disconnected or being AFK.You will be redirected to lobby.");
						window.location = 'lobby.html';
					}
				},
				success : function(data) {
					if (data.search("start") != -1) {
						countDownTimer();
						player1Name = data.slice(5).split(",", 2)[1];
						player2Name = data.slice(5).split(",", 2)[0];
						setEnemyName(player2Name);
						strikeAllow = true;
						sendToChat("<p>You may start shooting.</p>");
					} else if (data === "") {
					} else if (data==="error"){
						pollEnable = false;
						alert("Your opponent has disconnected or being AFK. You will be redirected to lobby.");
						window.location = 'lobby.html';

					} else {
						if (data.search("name=") != -1) {
							player1Name = data.slice(5).split(",", 2)[1];
							player2Name = data.slice(5).split(",", 2)[0];
							setEnemyName(player2Name);
						} else {
							if (moveCount == 0) {
								moveCount = 1;
							}
							opponentStrike(data);
							console.log("GameIndex: " + gameIndex);
							if (localStorage["g" + gameIndex
							                 + "player1"] == null) {
								localStorage["g" + gameIndex
								             + "player1"] = player1Name;
								localStorage["g" + gameIndex
								             + "player2"] = player2Name;
							}
							console.log("Players: "
									+ localStorage["g" + gameIndex
									               + "player1"],
									               localStorage["g" + gameIndex
									                            + "player2"]);
							console.log("Move number"
									+ localStorage["g" + gameIndex
									               + "move" + moveCount]
									+ "was added to the storage");
							moveCount++;
						}
					}
				},
				complete : function() {
					poll(arg);
				}
			});
		} else {
			$
			.ajax({
				url : "test",
				type : "POST",
				data : arg1,
				dataType : "json",
				success : function(data) {
					if (!(data["isFinished"])) {
						strike(data["cellId"], data["health"],
								data["dir"], data["len"]);
						console.log("GameIndex: " + gameIndex);
						console.log("Players: "
								+ localStorage["g" + gameIndex
								               + "player1"], localStorage["g"
								                                          + gameIndex + "player2"]);
						if (localStorage["g" + gameIndex + "player1"] == null) {
							localStorage["g" + gameIndex + "player1"] = player1Name;
							localStorage["g" + gameIndex + "player2"] = player2Name;
							console.log("Players: "
									+ localStorage["g" + gameIndex
									               + "player1"],
									               localStorage["g" + gameIndex
									                            + "player2"]);
						}
						if (moveCount == 0) {
							moveCount = 1;
						}
						localStorage["g" + gameIndex + "move"
						             + moveCount] = JSON.stringify(data);
						console.log("Move number"
								+ localStorage["g" + gameIndex + "move"
								               + moveCount]
								+ "was added to the storage")
								moveCount++;
					} else if (data === "") {
					} else {
						strike(data["cellId"], data["health"],
								data["dir"], data["len"]);
						localStorage["g" + gameIndex + "move"
						             + moveCount] = JSON.stringify(data);
						sendToChat("<p>You've won! Congratulations!</p>");
						pollEnable = false;
						clearInterval(countdown);
						$('#buttons').hide("slow");
					}
				}
			});
		}
	}
}
function checkIfReady() {
	handleStatusWindow();
}
function opponentStrike(targetId) {
	var mData = null;
	var target = $('#' + targetId).data("ship");
	if (target != undefined && $('#' + targetId).data("ship").health > 0) {
		playSound("hit");
		target.isShot = true;
		target.health--;
		mData = {
				'cellId' : targetId,
				'health' : target.health,
				'dir' : target.direction,
				'len' : target.coordinates.length,
				'x' : 1
		};
		$('#' + targetId).attr("isClicked", true);
		$('#' + targetId).prepend(
		'<img class="missOpponent" src="images/hit.gif"/>');
		strikeAllow = false;
		if ($('#' + targetId).data("ship").health == 0) {
			mData = {
					'cellId' : $('#' + targetId).data("ship").coordinates[0],
					'health' : target.health,
					'dir' : target.direction,
					'len' : target.coordinates.length,
					'x' : 1
			};
			playSound("sank");
			playerSankShipCount++;
			clearDivs($('#' + targetId).data("ship").coordinates);
			if (target.direction) {
				$('#' + $('#' + targetId).data("ship").coordinates[0])
				.html(
						'<img class="missOpponent" src="images/'
						+ $('#' + targetId).data("ship").coordinates.length
						+ 'point.png" />').animate({
							opacity : 0.4
						}, 800);
			} else {
				$('#' + $('#' + targetId).data("ship").coordinates[0])
				.html(
						'<img class="missOpponent" src="images/'
						+ $('#' + targetId).data("ship").coordinates.length
						+ 'pointR.png" />').animate({
							opacity : 0.4
						}, 800);
			}
			strikeAllow = false;
		}
	} else {
		mData = {
				'cellId' : targetId,
				'health' : -1,
				'dir' : false,
				'len' : -1,
				'x' : 1
		};
		playSound('miss');
		$('#' + targetId).html(
		'<img class="missOpponent" src="images/miss.png" />').animate({
			opacity : 0.6
		}, 800);
		strikeAllow = true;
		count = 60;
		sendToChat("<p>It's your turn to shoot.</p>");
		countDownTimer();
	}
	localStorage["g" + gameIndex + "move" + moveCount] = JSON.stringify(mData);
	checkIfLose();
}
function checkIfLose() {
	if (playerSankShipCount == 1) {
		sendToChat("<p>Sorry, but you've lost.</p>");
		pollEnable = false;
	}
}
function strike(targetId, health, dir, len) {
	if (health > 0) {
		playSound("hit");
		$('#enemy' + targetId).html(
		'<img class="missOpponent" src="images/hit.gif"/>');
		sendToChat("<p>You've hit opponent's ship! Shoot again.</p>");
		strikeAllow = true;
		count = 60;
	} else if (health == 0) {
		playSound("sank");
		clearDivs2(targetId, len, dir);
		if (dir) {
			$('#enemy' + targetId).html(
					'<img class="missOpponent" src="images/' + len
					+ 'point.png" />').animate({
						opacity : 0.4
					}, 800);
		} else {
			$('#enemy' + targetId).html(
					'<img class="missOpponent" src="images/' + len
					+ 'pointR.png" />').animate({
						opacity : 0.4
					}, 800);
		}
		sendToChat("<p>You've sank opponent's ship! Shoot again.</p>");
		strikeAllow = true;
		count = 60;
	} else {
		playSound('miss');
		$('#enemy' + targetId).prepend(
		'<img class="missOpponent" src="images/miss.png"/>').animate({
			opacity : 0.6
		}, 800);
		sendToChat("<p>You've missed. It's opponent's turn to shoot.</p>");
		strikeAllow = false;
		clearInterval(countdown);
		$('#buttons').hide("slow");
	}
}
function consist(array, elem) {
	for ( var i = 0; i < array.length; i++) {
		if (elem == array[i]) {
			return true;
		}
	}
	return false;
}
function createNewShip(element, target) {
	var src = element.attr('src');
	var len = parseInt(element.attr('alt').replace("Ship", ''));
	var first = parseInt(target.attr('id').replace('id', ''));
	var ar = new Array();
	var undropAr = new Array();
	var dir = true;
	if (src.match(/R/)) {
		dir = false;
	}
	for ( var i = 0; i < len; i++) {
		if (dir) {
			ar[i] = 'id' + (first + i);
			var a = [ first + i, first + i - 10, first + i + 10 ];
			for ( var j = 0; j < a.length; j++) {
				if (a[j] > -1 && a[j] < 100) {
					undropAr.push('id' + a[j]);
				}
			}
		} else {
			ar[i] = 'id' + (first + i * 10);
			var a = [ first + i * 10, first + i * 10 - 1, first + i * 10 + 1 ];
			for ( var j = 0; j < a.length; j++) {
				if (a[j] > -1 && a[j] < 100) {
					undropAr.push('id' + a[j]);
				}
			}
		}
	}
	var last = parseInt(ar[ar.length - 1].replace('id', ''));
	if (dir) {
		var a = [ first - 11, first - 1, first + 9, last - 9, last + 1,
		          last + 11 ];
		for ( var i = 0; i < a.length; i++) {
			if (a[i] > -1 && a[i] < 100) {
				undropAr.push('id' + a[i]);
			}
		}
	} else {
		var a = [ first - 11, first - 10, first - 9, last + 9, last + 10,
		          last + 11 ];
		for ( var i = 0; i < a.length; i++) {
			if (a[i] > -1 && a[i] < 100) {
				undropAr.push('id' + a[i]);
			}
		}
	}
	var left = new Array();
	var right = new Array();
	for ( var i = 0; i < 10; i++) {
		left[i] = 'id' + (i * 10);
		right[i] = 'id' + (9 + 10 * i);
	}
	for ( var i = 0; i < left.length; i++) {
		if (left[i] == ('id' + first)) {
			for ( var z = 0; z < undropAr.length; z++) {
				for ( var k = 0; k < right.length; k++) {
					if (undropAr[z] == right[k]) {
						removeByIndex(undropAr, z);
					}
				}
			}
			break;
		}
	}
	for ( var i = 0; i < right.length; i++) {
		if (right[i] == ('id' + first) || right[i] == ('id' + last)) {
			for ( var z = 0; z < undropAr.length; z++) {
				for ( var k = 0; k < left.length; k++) {
					if (undropAr[z] == left[k]) {
						removeByIndex(undropAr, z);
					}
				}
			}
			break;
		}
	}
	var newship = new ship(ar, undropAr, dir, src);
	$('#' + ar[0]).data("ship", newship);
	playersShipArray.push(newship);
	makeUndroppableCells(undropAr);
	PopulateDivs(newship);
}
function makeUndroppableCells(array) {
	for ( var i = 0; i < array.length; i++) {
		$('#' + array[i]).droppable("disable");
	}
}
function makeDroppableCells(array) {
	for ( var i = 0; i < array.length; i++) {
		$('#' + array[i]).droppable("enable");
	}
}
function removeByElement(arrayName, arrayElement) {
	for ( var i = 0; i < arrayName.length; i++) {
		if (arrayName[i] == arrayElement)
			arrayName.splice(i, 1);
	}
}
function restoreCells() {
	for ( var i = 0; i < playersShipArray.length; i++) {
		makeUndroppableCells(playersShipArray[i].undropCoordinates);
	}
}
function removeShip(id) {
	removeByElement(playersShipArray, $("#" + id).data("ship"));
	makeDroppableCells($("#" + id).data("ship").undropCoordinates);
	var k = $("#" + id).data("ship").coordinates;
	for ( var i = 0; i < k.length; i++) {
		$("#" + k[i]).removeData("ship");
	}
	restoreCells();
}
function removeByIndex(arrayName, arrayIndex) {
	arrayName.splice(arrayIndex, 1);
}
function PopulateDivs(shipObject) {
	for ( var int = 0; int < shipObject.coordinates.length; int++) {
		$('#' + shipObject.coordinates[int]).data("ship", shipObject);
	}
}